/**
 * Created by xulu on 2017/11/28.
 */
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import path from 'path'
/*import { Link } from 'react-router-dom'*/
import axios from 'axios'
import { Upload, Button, Modal, message, Icon } from 'antd'
import { apiUrl } from '../../api/constant'
import RecordTable from '../RecordTable'
const Dragger = Upload.Dragger
//const userAgent = navigator.userAgent

class FileOperation extends Component {
    static propTypes = {
        history: PropTypes.object,
        type: PropTypes.string.isRequired,
        fileList: PropTypes.array,
        limit: PropTypes.number,
        fileType: PropTypes.array,
        data: PropTypes.object,
        errMessage: PropTypes.string,
        upload: PropTypes.func
    };

    static defaultProps = {
        fileList: [],
        limit: 1,
        uploadUrl: `${apiUrl}/file/fileUpload`,
        downloadUrl: `${apiUrl}/file/fileDownload`
    };

    constructor(props) {
        super(props);

        this.state = {
            loading: false,
            visibal: false,
            uploadVisible: false,
            fileList: [],
            reloadRecordTable: false,
        };
    }

    componentWillMount() {
    }

    componentDidMount() {
    }

    componentWillReceiveProps(nextProps) {
    }

    handleBeforeUpload = (file) => {
        const {fileType} = this.props;
        if(fileType) {
            const isExt = fileType.filter(item => {
                    return item === path.extname(file.name).substring(1)
                }).length > 0;
            if (!isExt) {
                message.error('请上传正确的文件');
                return false;
            }
        }
        this.setState({
            fileList: [file],
        });
        /*let flag = file.size > fileSize
         if (flag) {
         message.error(`${file.name}大小超过限制`)
         return !flag;
         }*/
        return false;
    }

    handleOnChange = ({file, fileList}) => {
        if(file.status === 'done') {
            this.setState({
                loading: false
            })
            if(file.response.status === 200) {
                this.setState({
                    visible: true
                })
            } else {
                message.error(`文件 ${file.name} 上传失败！`);
            }
        } else if (file.status === 'error') {
            message.error(`文件 ${file.name} 上传失败！`);
            this.setState({
                loading: false
            })
        }
    }

    handleFileExport = () => {
        const {queryData} = this.props;
        const _this = this;
        let flag = false;
        if(queryData.city && queryData.city === '全部') {
            queryData.city = ''
        }
        for(let key in queryData) {
            if(queryData[key] && queryData[key]._isAMomentObject) {
                queryData[key] = queryData[key].format('YYYY-MM-DD');
                flag = true
            }
            if(queryData[key] && queryData[key].length > 0) {
                flag = true;
            }
        }
        if(flag) {
            this.handleFileExportAction()
        } else {
            Modal.confirm({
                title: '是否确认导出?',
                content: '当前导出数据量过大，建议条件筛选后再导出！',
                onOk() {
                    _this.handleFileExportAction()
                },
                onCancel() {},
            });
        }
    }

    handleFileExportAction = () => {
        const {downloadUrl, queryData, type} = this.props;
        const data = encodeURI(JSON.stringify({
            ...queryData,
            type: type
        }))
        this.setState({
            loading: true
        })
        axios({
            method:'post',
            url:`${downloadUrl}?data=${data}`,
            headers:{
                'Content-type': 'application/x-www-form-urlencoded'
            },
        }).then(res => {
            if(res.status === 200) {
                this.setState({
                    visible: true,
                    reloadRecordTable: true,
                })
            } else {
                message.error('导出文件失败！')
            }
            this.setState({
                loading: false
            })
        }).catch(() => {
            message.error('导出文件失败！');
            this.setState({
                loading: false
            })
        })
    }

    handleFileImport = () => {
        this.setState({
            uploadVisible: true
        })
    }

    handleOk = () => {
        const url = this.props.type.indexOf('Import') !== -1 ? '/record/import' : '/record/export'
        this.setState({
            visible: false,
            reloadRecordTable: false,
        })
        this.props.history.push(url)
    }

    handleCancel = () => {
        this.setState({
            visible: false,
            reloadRecordTable: false,
        })
    }

    handleUploadOk = () => {
        const {uploadUrl, type} = this.props;
        const { fileList } = this.state;
        if(fileList.length === 0) {
            message.error('请选择文件!');
            return false;
        }
        const formData = new FormData();
        formData.append('file', fileList[0]);
        formData.append('type', type);
        this.setState({
            loading: true
        })
        axios({
            method:'post',
            url: uploadUrl,
            data: formData,
            headers:{
                'Content-type': 'application/x-www-form-urlencoded'
            },
            timeout: 1000000,
        }).then(res => {
            if(res.status === 200) {
                this.setState({
                    visible: true,
                    uploadVisible: false,
                    fileList: [],
                    reloadRecordTable: true,
                })
            } else {
                message.error('上传文件失败！')
            }
            this.setState({
                loading: false
            })
        }).catch(() => {
            message.error('上传文件失败！');
            this.setState({
                loading: false
            })
        })
    }

    handleUploadCancel = () => {
        this.setState({
            uploadVisible: false,
            fileList: []
        })
    }

    handleFileRemove = () => {
        this.setState({
            fileList: []
        })
    }

    handleDownloadTemplate = () => {
        if(navigator.userAgent.indexOf("Chrome") === -1) {
            window.open(`${apiUrl}${this.props.templateUrl}`,'')
        }
    }

    render() {
        const {type, style, buttonText, buttonProps, actionUrl, limit, templateUrl} = this.props;
        const props = {
            name: 'file',
            action: actionUrl,
            limit: limit,
            showUploadList: true,
            fileList: this.state.fileList,
            data: {type: type}
        };

        return (
            <div style={{...style, display: 'inline-block'}}>
                {type === 'template' ?
                    <Button {...buttonProps} onClick={this.handleDownloadTemplate}>
                        {navigator.userAgent.indexOf("Chrome") > -1 ?
                            <a href={`${apiUrl}${templateUrl}`}>下载模板</a> :
                            <span>下载模板</span>}
                    </Button> :
                    <div>
                        {type.indexOf('Import') !== -1 ?
                            <Button {...buttonProps} loading={this.state.loading}
                                                     onClick={this.handleFileImport}>{buttonText}</Button> :
                            <Button {...buttonProps} loading={this.state.loading}
                                                     onClick={this.handleFileExport}>{buttonText}</Button>
                        }
                        <Modal
                            width={900}
                            maskClosable={false}
                            title="操作成功"
                            okText="查看结果"
                            visible={this.state.visible}
                            onOk={this.handleOk}
                            onCancel={this.handleCancel}
                            >
                            <p>{`文件正在处理中，可前往记录查询页面查看处理结果。`}</p>
                            <RecordTable type={type.indexOf('Import') !== -1 ? 'import' : 'export'}
                                         reload={this.state.reloadRecordTable}/>
                        </Modal>
                        <Modal
                            title="上传文件"
                            maskClosable={false}
                            visible={this.state.uploadVisible}
                            onOk={this.handleUploadOk}
                            onCancel={this.handleUploadCancel}
                            confirmLoading={this.state.loading}
                            >
                            <div style={{ margin: '15px 50px 50px', height: 180 }}>
                                <Dragger {...props} beforeUpload={this.handleBeforeUpload}
                                                    onChange={this.handleOnChange}
                                                    onRemove={this.handleFileRemove}>
                                    <p className="ant-upload-drag-icon">
                                        <Icon type="inbox" />
                                    </p>
                                    <p className="ant-upload-text">点击或拖动文件至此区域</p>
                                </Dragger>
                            </div>
                        </Modal>
                    </div>
                }
            </div>
        )
    }
}
export default FileOperation
